package ltd.nullpointer.tcp.core;

import com.boot2.core.utils.ByteUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.ReferenceCountUtil;
import ltd.nullpointer.tcp.core.constant.TCPEnum;
import ltd.nullpointer.tcp.core.exception.MessageSerializerException;
import ltd.nullpointer.tcp.core.message.AbstractTCPMessage;
import ltd.nullpointer.tcp.core.message.ErrorMessage;
import ltd.nullpointer.tcp.core.serialize.MessageSerializerFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author zhangweilin
 * @ClassName: MessageEncoder
 * @Description: 编码器
 * @date 2017年11月9日 下午1:25:39
 */
public class MessageEncoder extends MessageToByteEncoder<AbstractTCPMessage> {
    public Log log = LogFactory.getLog(this.getClass());

    @Override
    protected void encode(ChannelHandlerContext ctx, AbstractTCPMessage abstractMessage, ByteBuf out) throws Exception {
        ByteBuf messageByteBuf = null;
        try {
            messageByteBuf = MessageSerializerFactory.getInstance().serialize(abstractMessage);
//            byte[] byteArr = messageByteBuf.array();
            out.writeBytes(messageByteBuf);
            if (log.isDebugEnabled()) {
                messageByteBuf.resetReaderIndex();
                messageByteBuf.resetWriterIndex();
                byte[] byteArr = messageByteBuf.array();
                String str = ByteUtils.hexBytes2HexString(byteArr);
                log.debug("下发完整hex报文 str: " + str);
                byteArr = null;
            }
//            String str = ByteUtils.hexBytes2HexString(byteArr);
//            byteArr = null;
//            log.debug("下发完整hex报文 str: " + str);
//			log.debug("MessageEncoder.encode: "+abstractMessage);
//			log.debug("MessageEncoder.encode.byte[]: "+Arrays.toString(byteArr));
        } catch (MessageSerializerException e) {
            e.printStackTrace();
            ErrorMessage errorMessage = new ErrorMessage(e.getErrCode(), e.getMessage());
            ctx.channel().writeAndFlush(errorMessage);
        } catch (Exception e) {
            e.printStackTrace();
            ErrorMessage errorMessage = new ErrorMessage(TCPEnum.ErrorCode.err10015);
            ctx.channel().writeAndFlush(errorMessage);
        }
        finally {
            messageByteBuf.release();
            ReferenceCountUtil.release(abstractMessage);
        }
    }
}
